package com.cj.common.config.handerconfig;

import com.cj.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Author cheng jun
 * @Description: 请求拦截，避免服务绕过接口被直接访问
 * @Date 2021/8/7 14:40
 */

/**
 * 支持Nacos的动态刷新功能
 */
@RefreshScope
@Component
@Slf4j
public class GatewayInterceptor implements HandlerInterceptor {

    @Value("${org.my.jwt.jwt-header-name}")
    private String jwtHeaderName;

    @Value("${org.my.jwt.jwt-header}")
    private String jwtHeader;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("端口:" + request.getServerPort() + ",接口:" + request.getRequestURI() + ",拦截器执行afterCompletion方法，调用结束-------------------------------------------");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        log.info("端口:" + request.getServerPort() + ",接口:" + request.getRequestURI() + ",拦截器执行postHandle方法-----------------------------------------");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("端口:" + request.getServerPort() + ",接口:" + request.getRequestURI() + ",进入拦截器-------------------------------------------");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 带有@IgnoreToken注解的不拦截
        if (method.isAnnotationPresent(IgnoreToken.class)) {
            return true;
        }

        String gateway = request.getHeader(jwtHeaderName);
        if( null == gateway || Objects.equals("", gateway) || !Objects.equals(gateway, jwtHeader)){
            throw new BaseException("端口:" + request.getServerPort() + ",接口:" + request.getRequestURI() + ",请走网关-------------------------------------------");
        }

        return true;
    }
}
